package com.onetech.adrewards.free.fragments;

import java.util.List;

import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.activities.BaseNewActivity;
import com.onetech.adrewards.free.adapters.ListGiftCardAdapter;
import com.onetech.adrewards.free.config.AppConfig;
import com.onetech.adrewards.free.customviews.LoadMoreListView;
import com.onetech.adrewards.free.dialogs.MessageDialog;
import com.onetech.adrewards.free.dialogs.RegisterEmailConfirmDialog;
import com.onetech.adrewards.free.models.ListGiftCardModel;
import com.onetech.adrewards.free.objects.ListGiftCardDTO;
import com.onetech.adrewards.free.objects.UserInfoDTO;

public class ListGiftCardFragment extends BaseAdsFragment implements OnItemClickListener {
	private ListGiftCardAdapter mAdapter;
	protected LoadMoreListView mListView;
	protected View mNotFoundData=null;
	protected int pageNo=1;
	protected int userCoins;
	protected View mWaitingForLoading=null;
	//private LoadGiftCardUserExchanged mLoadGiftCardUserExchange = null;
	private LoadListGiftCard mLoadListGiftCard = null;
	//private UserInfoDTO mUserInfo = null;

	private MessageDialog mMessage = null;
	private DoExchange mDoExchange=null;
	
	private int selectedPosition = -1;
	private View mGetCoiBtn = null;
	
	private View mExchangeContainer = null;
	private View mGetCoinContainer = null;
	private TextView mExchangeMessage = null;
	private TextView mGetCoinMessage = null;
	private Bundle params = null;
	public interface GiftCarFragmentInterface{
		public void setCurrentItem(int index);
	}
	private GiftCarFragmentInterface mGiftCarFragmentInterface=null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mView == null) {
			mView = inflater.inflate(R.layout.exchange_activity_layout,
					container, false);
			initView();
			initListener();
		} else {
			((ViewGroup) mView.getParent()).removeView(mView);
		}
		return mView;
	}

	private void initView() {
		
		mExchangeContainer = (LinearLayout)mView.findViewById(R.id.exchangeContainer);
		mGetCoinContainer = (LinearLayout)mView.findViewById(R.id.getCoinContainer);
		mExchangeMessage = (TextView)mView.findViewById(R.id.exchangeMessage);
		
		mExchangeMessage.setText(mExchangeMessage.getText().toString().replace("[min_exchange_coin]", String.valueOf(AppConfig.MIN_COIN_EXCHANGE)));
		
		
		mGetCoinMessage = (TextView)mView.findViewById(R.id.getCoinMessage);
		
		
		mGetCoiBtn = (LinearLayout) mView.findViewById(R.id.getCoinBtn);
		
		mListView = (LoadMoreListView)mView.findViewById(R.id.myExchangeListView);
		mListView.setVisibility(View.GONE);
		mAdapter = new ListGiftCardAdapter(getActivity());
		mListView.setAdapter(mAdapter);
		
		switchShowOrHideView(false, false);
		initNotFoundAndLoadingView();
		
		mGiftCarFragmentInterface=new GiftCarFragmentInterface() {
			
			@Override
			public void setCurrentItem(int index) {
				ListGiftCardFragment.this.switchCurrentItem(index);
			}
		};
	}

	private void initListener() {
		initRetryButtonListener();
		
		mListView.setOnItemClickListener(this);
		
		mGetCoiBtn.setOnClickListener(this);
		
	}
	@Override
	public void onResume() {
		userCoins = ((BaseNewActivity)getActivity()).getUserCoins();
		String msg = getActivity().getString(R.string.get_gift_card_now);
		msg = msg.replace("[min_exchange_coin]", String.valueOf(AppConfig.MIN_COIN_EXCHANGE - userCoins));
		mGetCoinMessage.setText(Html.fromHtml(msg));
		super.onResume();
		if (mAdapter != null && mAdapter.getCount() < 1) {
			loadListGiftCard();
		}
		
		checkUserCoins();
	}
	private void switchShowOrHideView(boolean isShowExchange,
			boolean isShowGetCoin) {
		mExchangeContainer.setVisibility(isShowExchange ? View.VISIBLE
				: View.GONE);
		mGetCoinContainer.setVisibility(isShowGetCoin ? View.VISIBLE
				: View.GONE);
	}

	private void checkUserCoins() {
		try {			
			if (userCoins >= AppConfig.MIN_COIN_EXCHANGE) {
				switchShowOrHideView(true, false);
			} else {
				switchShowOrHideView(false, true);
			}
		} catch (Exception e) {
		}
	}

	private void loadListGiftCard() {
		if (mLoadListGiftCard == null
				|| mLoadListGiftCard.getStatus() == Status.FINISHED) {
			mLoadListGiftCard = new LoadListGiftCard();
			mLoadListGiftCard.execute();
		}
	}
	private class LoadListGiftCard extends AsyncTask<Void, Void, List<ListGiftCardDTO>> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showNotFoundOrLoadingView(false, true);
			
		}

		@Override
		protected List<ListGiftCardDTO> doInBackground(Void... params) {
			try {
				return ListGiftCardModel.getInstance().getListGiftCard(String.valueOf(pageNo));
			} catch (Exception e) {
				return null;
			}
		}
		
		@Override
		protected void onPostExecute(List<ListGiftCardDTO> result) {
			super.onPostExecute(result);
			try {
				if (result != null) {
					if (result.size() < 1) {
						if (mAdapter.getCount() < 1) {
							showNotFoundOrLoadingView(false, false);
							
							mListView.setVisibility(View.GONE);
						} else {
							
							showNotFoundOrLoadingView(false, false);
							mListView.setVisibility(View.VISIBLE);
						}						
					} else {
						if (pageNo == 1) {
							mAdapter.updateAppList(result);
						} else {
							mAdapter.insertAppList(result);
						}
						pageNo++;
						showNotFoundOrLoadingView(false, false);
						mListView.setVisibility(View.VISIBLE);
					}
				} else {
					if (mAdapter.getCount() < 1) {
						showNotFoundOrLoadingView(true, false);
						
						mListView.setVisibility(View.GONE);
					} else {
						
						showNotFoundOrLoadingView(false, false);
						mListView.setVisibility(View.VISIBLE);
					}
				}
			} catch (Exception e) {
			}
			mListView.onLoadMoreComplete();
		}
	}
//	@Override
//	public void onLoadMore() {
//		
//		loadListGiftCard();
//	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		
		case R.id.btnRetry:
			pageNo = 1;
			mListView.setVisibility(View.VISIBLE);
			showNotFoundOrLoadingView(false, true);
			loadListGiftCard();
			break;
		
		case R.id.getCoinBtn:
			switchCurrentItem(1);
			break;
		default:
			super.onClick(v);
			break;
		}
	}

	public void switchCurrentItem(int index) {
		((ExchangeFragmentNew) getParentFragment()).switchCurrentItem(index);
	}
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		try {
			if(position>mAdapter.getCount()-1){
				return;
			}
			this.selectedPosition = position;
			doExchange();
		
		} catch (Exception e) {
			return;
		}
	}
	
	
	protected void doExchange(){
		
		if(mAdapter!=null){
			if(mDoExchange==null || mDoExchange.getStatus()==Status.FINISHED){
				mDoExchange=new DoExchange();
				mDoExchange.execute();
			}
		}		
	}
	
	protected class DoExchange extends AsyncTask<Void, Void, UserInfoDTO>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showNotFoundOrLoadingView(false, true);
			
		}
		@Override
		protected UserInfoDTO doInBackground(Void... params) {
			try
			{
				return ListGiftCardModel.getInstance().validate(AppConfig.uId);
			}
			catch(Exception ex)
			{
				return null;
			}
		}
		@Override
		protected void onPostExecute(UserInfoDTO result) {
			super.onPostExecute(result);
		
			if(result == null)
			{
				return;
			}
			
			userCoins = Integer.valueOf(result.getTotal_coin());
			int email = -1;
			ListGiftCardDTO item = mAdapter.getItem(selectedPosition);
			
			if(userCoins < item.getCoin())
			{
				params = new Bundle();
				params.putString("discount", String.valueOf(item.getDiscount()));
				mMessage = new MessageDialog(getActivity(), 1, params, getActivity().getString(R.string.exchange_title),mGiftCarFragmentInterface);
				mMessage.show();
			}
			else
			{
				email = Integer.valueOf(result.getEmail());
				if(email < 1)
				{
					result.setuId(AppConfig.uId);
					
					RegisterEmailConfirmDialog confirm = new RegisterEmailConfirmDialog(getActivity(), result);
					confirm.show();
					

				}
				else
				{
					//Show dialog exchange
					params = new Bundle();
					params.putString("current_coin", String.valueOf(userCoins));
					params.putString("discount", String.valueOf(item.getDiscount()));
					params.putString("card_name", item.getName());
					params.putString("type", String.valueOf(item.getId()));
					mMessage = new MessageDialog(getActivity(), 2, params, getActivity().getString(R.string.exchange_title),mGiftCarFragmentInterface);
					mMessage.show();
				}
				
			}
			
		}
	}


	@Override
    public void onStart() {
        super.onStart();
        try {
            mTracker.set(Fields.SCREEN_NAME, getActivity().getString(R.string.ExchangeFragment));            
            mTracker.send(MapBuilder.createAppView().build());            
		} catch (Exception e) {
		}
    }
			
}
	

